//
//  WBOAuthViewController.swift
//  mySwiftVV
//
//  Created by hu yr on 2017/1/3.
//  Copyright © 2017年 terry. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 通过 webView 加载新浪微博授权页面控制器
class WBOAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        view.backgroundColor = UIColor.white
        // 取消视图滚动 - 新浪微博返回的 视图默认是全屏的
        webView.scrollView.isScrollEnabled = false
        
        //设置代理
        webView.delegate = self
        
        
        //设置导航栏
        title = "登录新浪微博"
        //导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBackButton: true)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        //加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        
        /// 1.URL 确定更要访问的资源
        guard let url = URL(string: urlString)else{
                return
        }
        //2.建立请求
        let request = URLRequest(url: url)
        
        //3.加载请求
        webView.loadRequest(request)
        
    }

    // MARK : -监听方法
    //关闭控制器
    @objc fileprivate func close(){
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true) { 
            
        }
    }
    
    /// 自动填充 - webView 的注入, 直接通过 js 修改 '本地浏览器中' 缓存的页面内容
    //点击登录按钮, 执行submit() 将本地数据提交给服务器
    @objc fileprivate func autoFill(){
        
        //准备JS
        let js = "document.getElementById('userId').value = 'ichina66@sina.com'; " +
        "document.getElementById('passwd').value = '86738165123lxlk';"
        //让webView执行 js
        webView.stringByEvaluatingJavaScript(from: js)
    }
    
    

}
extension WBOAuthViewController: UIWebViewDelegate{
    
    /// webView 将要加载请求
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //确认思路:
        //1.如果请求地址包含 http://baidu.com 不加载页面 / 否则加载页面
        
        if request.url?.absoluteString.hasPrefix(WBRedirectURI) == false{
            return true
            
        }
        
//        print("加载请求 --- \(request.url?.absoluteString)")
//        query就是 URL 中 ? 后面的所有部分
//        print("加载请求 --- \(request.url?.query)")
        
        //2.从http://baidu.com 回调地址中的查询字符串中查找'code='
        //3.如果有,授权成功,否则,授权失败
        if request.url?.query?.hasPrefix("code=") == false{
            print("取消授权")
            
            close()
            
            return false
        }
        //3.从query 字符串中 取出授权码
        //代码走到此处,url 中一定有 查询字符串, 并且 包含'code='
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print(" 授权码code --> \(code)")
        //4.使用授权码获取 AccessToken
        WBNetWorkManager.shared.loadAccessToken(code: code) { (isSucess) in
            
            if !isSucess{
                
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
                
            }else{
                
//                SVProgressHUD.showInfo(withStatus: "登录成功")
                
                //1.发送用户登录成功的通知消息
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessedNotification), object: nil)
                
                //2.关闭窗口
                self.close()
            }
        }
        
        return false
    }
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
